package com.anonymous.community;

import android.app.Application;
import android.content.Context;
import androidx.multidex.MultiDex;
import com.anonymous.community.api.ApiClient;
import com.anonymous.community.hotfix.HotfixManager;
import com.tencent.bugly.crashreport.CrashReport;
// import com.tencent.bugly.beta.Beta; // 注释掉Beta导入，因为crashreport_upgrade依赖不可用

public class CommunityApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        
        // 初始化ApiClient
        ApiClient.init(this);
        
        // 初始化Bugly
        initBugly();
        
        // 初始化热更新管理器
        initHotfixManager();
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }
    
    /**
     * 初始化Bugly
     */
    private void initBugly() {
        // 获取当前包名
        String packageName = this.getPackageName();
        // 获取当前进程名
        String processName = getProcessName(android.os.Process.myPid());
        // 设置是否为上报进程
        CrashReport.UserStrategy strategy = new CrashReport.UserStrategy(this);
        strategy.setUploadProcess(processName == null || processName.equals(packageName));
        
        // 启用运营统计 - 注释掉Beta相关代码，因为crashreport_upgrade依赖不可用
        // Beta.enableHotfix = false; // 关闭热更新功能，只使用统计功能
        // Beta.canShowUpgradeActs.add(MainActivity.class);
        
        // 初始化Bugly
        CrashReport.initCrashReport(this, "1f5023ea91", false, strategy);
    }
    
    /**
     * 获取进程号对应的进程名
     */
    private String getProcessName(int pid) {
        android.app.ActivityManager am = (android.app.ActivityManager) 
            getSystemService(Context.ACTIVITY_SERVICE);
        java.util.List<android.app.ActivityManager.RunningAppProcessInfo> runningApps = am.getRunningAppProcesses();
        if (runningApps == null) {
            return null;
        }
        for (android.app.ActivityManager.RunningAppProcessInfo procInfo : runningApps) {
            if (procInfo.pid == pid) {
                return procInfo.processName;
            }
        }
        return null;
    }
    
    /**
     * 初始化热更新管理器
     */
    private void initHotfixManager() {
        try {
            HotfixManager hotfixManager = HotfixManager.getInstance(this);
            // 启动时自动检查更新
            hotfixManager.checkForUpdates();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}